use crate::*;

use std::process::exit;
use std::sync::mpsc::{Receiver, Sender};
use web_view::*;

const COMMON_JS: &'static str = include_str!("browser-polyfill.js");
const VUE_JS: &'static str = include_str!("../../parcel-build/main.js");
const VUE_CSS: &'static str = include_str!("../../parcel-build/main.css");

pub fn run() {
    let _ = database::insert("init", "init-data", None);
    let d = database::select("init", None);
    println!("database {:?}", d);

    let html = format!(
        r#"<!doctype html>
		<html>
			<head>
			    <meta http-equiv="content-type" content="text/html;charset=utf-8">
			    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
				{styles}
			</head>
			<body>
				<div id="app">
				    <h1 style="text-align: center;">正在加载中...</h1>
				</div>
                {COMMON_JS}
                {scripts}
			</body>
		</html>"#,
        styles = inline_style(VUE_CSS),
        COMMON_JS = inline_script(COMMON_JS),
        scripts = inline_script(VUE_JS) //scripts = url_script("http://localhost:1234/main.1f19ae8e.js")
    );

    // 线程池开启
    // let pool = Pool::new(3);
    let pool = threadpool::Builder::default().num_threads(3).build();

    // 管道开启
    let (send, rever): (Sender<String>, Receiver<String>) = std::sync::mpsc::channel();

    let mut webview = web_view::builder()
        .title("股票行情信息观察 3.0.0-beta3")
        .content(Content::Html(html))
        // .content(Content::Url("http://127.0.0.1:1234/#/"))
        // .content(Content::Url("http://www.baidu.com"))
        .size(1366, 768)
        .resizable(true)
        .debug(true)
        .user_data((send, pool))
        .invoke_handler(|webview: &mut WebView<(Sender<String>, Pool)>, arg| {
            let user_data = webview.user_data();
            webview_handler::add_channel(user_data.0.clone(), &user_data.1, arg.to_string());
            Ok(())
        })
        .build()
        .unwrap();

    loop {
        if webview.step().is_none() {
            break;
        }

        // 接收消息
        if let Ok(exec_js) = rever.try_recv() {
            let _ = webview.eval(exec_js.as_str());
        }
    }

    // webview.eval("alert('程序启动了')");
    //let res = webview.lock().unwrap().run().unwrap();
    // tx.send(("cmd".to_owned(), "exit".to_owned()));
    println!("webview close");
    webview.exit();
    exit(0);
}

fn inline_style(s: &str) -> String {
    format!(
        r#"<style type="text/css">
    {}
    </style>"#,
        s
    )
}

fn inline_script(s: &str) -> String {
    format!(
        r#"<script type="text/javascript">
    {}
    </script>"#,
        s
    )
}
